package room

import (
	"gitee.com/jamon/espoir_go/common/utils"
	"gitee.com/jamon/espoir_go/frame"
	"math/rand"
	"time"
)

// ReadyStatus 准备状态
const (
	ReadyStatus_NOT_READY = 0 // 未准备
	ReadyStatus_READY     = 1 // 已准备
	REadyStatus_GAME_OVER = 2 // 游戏结束
)

// GameStatus 游戏状态
const (
	GameStatus_NOT_START = 0 // 未开始
	GameStatus_RUNNING   = 1 // 进行中
	GameStatus_GAME_OVER = 2 // 结束
)

// RoomType 房间类型
const (
	RoomType_Match  = 0 // 匹配房间
	RoomType_Friend = 1 // 好友房间
)

// GameType 游戏类型
const (
	GameType_Single = 0 // 单人游戏
	GameType_Double = 1 // 双人游戏
)

type BaseRoom struct {
	GameID        string
	GameType      uint8
	RoomType      uint8
	GameStatus    uint8
	MembersStatus utils.Map[uint64, uint8] // userID -> ReadyStatus
	FrameServer   *frame.Server

	RandSeed   int32
	CreateTime uint32
}

func NewBaseRoom(gameID string, gameType uint8, roomType uint8) *BaseRoom {
	return &BaseRoom{
		GameID:        gameID,
		GameType:      gameType,
		RoomType:      roomType,
		GameStatus:    GameStatus_NOT_START,
		MembersStatus: utils.NewMap[uint64, uint8](),
		CreateTime:    uint32(time.Now().Unix()),
		RandSeed:      int32(rand.Intn(1000000)),
	}
}

func (r *BaseRoom) isFull() bool {
	if r.GameType == GameType_Single {
		return r.MembersStatus.Len() == 1
	} else if r.GameType == GameType_Double {
		return r.MembersStatus.Len() == 2
	}
	return false
}

func (r *BaseRoom) isAllReady() bool {
	allReady := true
	r.MembersStatus.LockRange(func(key uint64, value uint8) {
		if value != ReadyStatus_READY {
			allReady = false
			return
		}
	})
	return allReady
}

func (r *BaseRoom) isAllOver() bool {
	allOver := true
	r.MembersStatus.LockRange(func(key uint64, value uint8) {
		if value != REadyStatus_GAME_OVER {
			allOver = false
			return
		}
	})
	return allOver
}

func (r *BaseRoom) isTimeout() bool {
	curTime := uint32(time.Now().Unix())
	return curTime-r.CreateTime > 60*10
}
